<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useSpeechRecognition } from '@vueuse/core';

const lang = ref("zh-CN")

const speech = useSpeechRecognition({
    lang,
    continuous: true
})

const textRef = ref<HTMLElement>(null);

const { isListening, isSupported, result, stop, error } = speech

const start = () => {
    // speech.result.value = ""
    speech.start()
}

nextTick()

watch(result, (result) => {
    if (result.length > 200) {
        speech.result.value = result.slice(100)
    }
    textRef.value.scrollBy(0, 100)
})

// onMounted(() => {
// setInterval(() => { textRef.value.scrollBy(0, 200); }, 1000)
// })

onBeforeUnmount(() => {
    stop()
})

</script>

<template>
    <div>
        <div v-if="!isSupported">
            Your browser does not support SpeechRecognition API,
            <a
                href="https://caniuse.com/mdn-api_speechrecognition"
                target="_blank"
            >more details</a>
        </div>
        <div v-else>
            <div :class="isListening ? 'disabled' : ''">
                <label>
                    <input type="radio" v-model="lang" value="zh-CN" :disabled="isListening" />
                    <span>zh-CN</span>
                </label>
                <label>
                    <input type="radio" v-model="lang" value="en-US" :disabled="isListening" />
                    <span>en-US</span>
                </label>
                <label>
                    <input type="radio" v-model="lang" value="ja" :disabled="isListening" />
                    <span>ja-JP</span>
                </label>
            </div>
            <div>
                <button v-if="!isListening" @click="start()">Press and talk</button>
                <button v-if="isListening" @click="stop()">Stop</button>
            </div>
            <div class="my-text" ref="textRef">{{ result }}</div>
            <div class="my-text">{{ error && error.message }}</div>
        </div>
    </div>
</template>

<style scoped>
.disabled {
    user-select: none;
    opacity: 0.5;
}
.my-text {
    /* font-family: "Dotted Songti Square", Avenir, Helvetica,
        Arial, sans-serif !important; */
    text-align: left;
    font-size: 1.5em;
    max-width: 800px;
    margin: 20px 20px;
    -webkit-text-stroke: 0.5px coral;
    height: 3em;
    overflow-y: scroll;
    /* scroll-behavior: smooth; */
    /* background-color: antiquewhite; */
}
</style>